//
//  pictureView.swift
//  XinLangWeibo10
//
//  Created by 白利兵 on 15/10/22.
//  Copyright © 2015年 itheima. All rights reserved.
//

import UIKit
import SDWebImage
let picUrls = "picUrls"
class StatusPictureView: UICollectionView {
    
    private let itemSpaceMargin: CGFloat = 8
    private let pictureViewCellReuseId = "pictureViewCell"
    var viewModel: StatusViewModel? {
        didSet {
            // 自动计算大小
            sizeToFit()
            // 刷新数据
            reloadData()
        }
    }
    // 重写自适应大小
    override func sizeThatFits(size: CGSize) -> CGSize {
        //print(calculateViewSize())
        return calculateViewSize()
    }
    // 构造函数
    
     init() {
        // 创建流式布局
        let layout = UICollectionViewFlowLayout()
        // 设置布局属性
        layout.minimumInteritemSpacing = itemSpaceMargin
        layout.minimumLineSpacing = itemSpaceMargin
        super.init(frame: CGRectZero, collectionViewLayout: layout)
        backgroundColor = UIColor(white: 0.8, alpha: 1.0)
        // 设置数据源
        dataSource = self
        // 设置代理
        delegate = self
        // 注册cell
        registerClass(StatusPictureViewCell.self, forCellWithReuseIdentifier:pictureViewCellReuseId)
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}
// MARK: - 代理方法
extension StatusPictureView: UICollectionViewDelegate {
    /// 选中照片
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        print("点击照片 \(indexPath) \(viewModel!.thumbnail_pic)")
        
        // 明确问题：传递什么数据？当前 URL 的数组／当前用户选中的索引
        // 如何传递：通知
        // 通知：名字(通知中心监听)/object：发送通知的同时传递对象(单值)/ userInfo 传递多值的时候，使用的数据字典 -> Key
        let userInfo = [WBStatusSelectedPhotoIndexPathKey: indexPath,WBStatusSelectedPhotoURLsKey: viewModel!.thumbnail_pic!]
        // 把当前图片索引传值给计算大小的协议方法
        photoBrowserPresentFromRect(indexPath)
        photoBrowserPresentToRect(indexPath)
        NSNotificationCenter.defaultCenter().postNotificationName(WBStatusSelectedPhotoNotification,
            object: self,
            userInfo: userInfo)
    }
}
// MARK: - 数据源方法
extension StatusPictureView: UICollectionViewDataSource {
    /// 数据源方法
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        return viewModel?.thumbnail_pic!.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(pictureViewCellReuseId, forIndexPath: indexPath) as! StatusPictureViewCell
            cell.imageURL = viewModel!.thumbnail_pic![indexPath.item]
            return cell
    }
}
// MARK: - 设置视图大小
extension StatusPictureView {
    // 重写设置大小
    func calculateViewSize() -> CGSize {
        
        // 1. 准备
        // 每行的照片数量
        let rowCount: CGFloat = 3
        // 最大宽度
        let maxWidth = UIScreen.mainScreen().bounds.width - 2 * StatusCellMargin
        let itemWidth = (maxWidth - 2 * itemSpaceMargin ) / rowCount
        
        // 2. 设置 layout 的 itemSize
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        
        // 3. 获取图片数量
        let count = viewModel?.thumbnail_pic?.count ?? 0
        
        // 计算开始
        // 1> 没有图片
        if count == 0 {
            return CGSizeZero
        }
        
        // 2> 一张图片
        if count == 1 {
            // TODO: - 临时指定大小，稍后再讲
            var size = CGSize(width: 150, height: 120)
            // 从模型中获取图片的key，然后获得图片
            if let key = viewModel?.thumbnail_pic?.first?.absoluteString {
                // 从沙盒缓存中取图片
                let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
                if image != nil {
                    size = image.size
                }
            }
            // 图片过窄的处理
            if size.width < 40 {
                let width: CGFloat = 40.0
                size = CGSizeMake(width, size.height)
            }
            
            // 图片过大的处理
            if size.width > 300 {
                let width: CGFloat = 300.0
                size = CGSizeMake(width, width * (size.height/size.width))
            }
            // 内部图片的大小
            layout.itemSize = size
            
            // 配图视图的大小
            return size
        }
        
        // 3> 四张图片 2 * 2 的大小
        if count == 4 {
            let w = 2 * itemWidth + itemSpaceMargin
            return CGSize(width: w, height: w)
        }
        
        // 4> 其他图片 按照九宫格来显示
        // 计算出行数
        /**
        2 3
        5 6
        7 8 9
        */
        let row = CGFloat((count - 1) / Int(rowCount) + 1)
        let h = row * itemWidth + (row - 1) * itemSpaceMargin
        let w = rowCount * itemWidth + (rowCount - 1) * itemSpaceMargin
        
        return CGSize(width: w, height: h)
    }
}
private class StatusPictureViewCell: UICollectionViewCell {
    var imageURL: NSURL? {
        didSet {
            iconView.sd_setImageWithURL(imageURL,
                placeholderImage: nil,                      // 在调用 OC 的框架时，可/必选项不严格
                options: [SDWebImageOptions.RetryFailed,    // SD 超时时长 15s，一旦超时会记入黑名单
                    SDWebImageOptions.RefreshCached])       // 如果 URL 不变，图像变
        }
    }
    
    // MARK: - 构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        // 1. 添加控件
        contentView.addSubview(iconView)
        
        // 2. 设置布局 - 提示因为 cell 会变化，另外，不同的 cell 大小可能不一样
        iconView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
        }
    }
    
    // MARK: - 懒加载控件
    private lazy var iconView: UIImageView = {
            let iconImage = UIImageView()
            // 设置填充模式
            iconImage.contentMode = UIViewContentMode.ScaleAspectFill
            // 切割
            iconImage.clipsToBounds = true
            return iconImage
        }()
    
}
extension StatusPictureView: PictureAnimatorPresentDelegate {
    // 图片位置索引
    func imageViewForPresent(indexPath: NSIndexPath) -> UIImageView {
        // 从图片缓存中取出图片
        let iv = UIImageView()
        let key = viewModel?.thumbnail_pic![indexPath.item].absoluteString
        iv.image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
        iv.contentMode = .ScaleAspectFill
        iv.clipsToBounds = true
        iv.sizeToFit()
        return iv
    }
    // 源图片的frame
    func photoBrowserPresentFromRect(indexPath: NSIndexPath) -> CGRect {
        guard let cell = self.cellForItemAtIndexPath(indexPath) else {
            return CGRectZero
        }
        
        let rect = self.convertRect(cell.frame, toCoordinateSpace: UIApplication.sharedApplication().keyWindow!)
        return rect
    }
    // 目标图片的frame
    func photoBrowserPresentToRect(indexPath: NSIndexPath) -> CGRect {
        let key = viewModel!.thumbnail_pic![indexPath.item].absoluteString
        guard let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key) else {
            return CGRectZero
        }
        
        let w = UIScreen.mainScreen().bounds.width
        let h = image.size.height * w / image.size.width
        var y: CGFloat = 0
        
        let screenHeight = UIScreen.mainScreen().bounds.height
        if h < screenHeight {
            y = (screenHeight - h) * 0.5
        }
        
        return CGRect(x: 0, y: y, width: w, height: h)
    }
}

